<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>车辆保养</title>
    <script src="/js/vue.js"></script>
    <script src="/js/axios.js"></script>
    <link rel="stylesheet" href="/element-ui/lib/theme-chalk/index.css">
    <script src="/element-ui/lib/index.js"></script>
    <style>
        .el-table th,.el-table .cell{
            text-align: center;
        }
        .el-dialog--center .el-dialog__body {
            padding-bottom: 0px;
        }
        .el-form-item {
            margin-bottom: 15px;
        }
        .el-radio__inner {border-radius: 2px;}
        .el-radio__input.is-checked .el-radio__inner::after {
            content: '';
            width: 8px;
            height: 3px;
            border: 2px solid white;
            border-top: transparent;
            border-right: transparent;
            text-align: center;
            display: block;
            position: absolute;
            top: 2px;
            left: 1px;
            vertical-align: middle;
            transform: rotate(-45deg);
            border-radius: 0px;
            background: none;
        }
    </style>
</head>
<body>
<div id="app">

    <el-card shadow="always">
        <div slot="header">
            <span>车服租赁管理</span>
        </div>
        <!-- 面包屑 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>基础信息管理</el-breadcrumb-item>
            <el-breadcrumb-item>车辆保养</el-breadcrumb-item>
        </el-breadcrumb>
    </el-card>

    <el-card shadow="always">
        <el-form :inline="true" :model="param" class="demo-form-inline">
            <el-form-item label="日期">
                <el-date-picker
                        v-model="param.maintenanceDate"
                        value-format="yyyy-MM-dd"
                        type="date"
                        placeholder="请选择查询日期" clearable>
                </el-date-picker>
            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="param.maintenanceState" placeholder="请选择状态" style="width: 120px">
                    <!-- 省略label，默认与value一样 -->
                    <el-option
                            v-for="item in types"
                            :key="item.maintenanceState"
                            :label="item.name"
                            :value="item.maintenanceState">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit" icon="el-icon-search" size="medium">查询</el-button>
                <el-button type="primary" @click="resetCondition" icon="el-icon-search" size="medium">重置</el-button>
                <el-button type="success" @click="showDialog" icon="el-icon-circle-plus" size="medium">添加</el-button>
                <el-button type="danger" size="medium" icon="el-icon-delete-solid" @click="deleteBatch">删除</el-button>
                <!--
              action: 上传地址
              name: 表单项名字，与控制器中MultipartFile类型的形参名字要一样
              show-file-list：隐藏上传的文件列表
              accept：限制选择的文件类型为Excel的类型
              display: inline 样式显示在同一行
              Excel格式：xls或xlsx
              -->
                <el-upload
                        style="display: inline; margin-left: 10px;"
                        action="/carHealth/import"
                        name="file"
                        :show-file-list="false"
                        accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                        :on-success="handleSuccess">
                    <el-button size="medium" type="primary" icon="el-icon-upload">导入Excel</el-button>
                </el-upload>
                <el-button type="warning" icon="el-icon-printer" size="medium" @click="exportExcel">导出Excel</el-button>
            </el-form-item>
        </el-form>

        <el-table
                :default-sort = "{prop: 'maintenanceDate', order: 'descending'}"
                ref="multipleTable"
                :data="pageBean.list"
                tooltip-effect="dark"
                style="width: 100%"
                @selection-change="handleSelectionChange">
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>

            <el-table-column
                    prop="carNumber"
                    label="车牌号"
                    width="110">
            </el-table-column>

            <el-table-column
                    prop="frameNumber"
                    label="车架号"
            width="120">
            </el-table-column>

            <el-table-column
                    sortable
                    prop="maintenanceDate"
                    label="保养日期"
            width="100">
            </el-table-column>

            <el-table-column
                    prop="maintenanceGrade"
                    label="保养等级"
            width="80">
                <template slot-scope="scope">
                    <el-tag v-if=" scope.row.maintenanceGrade===1" type="info">一级</el-tag>
                    <el-tag v-if=" scope.row.maintenanceGrade===2" type="warning">二级</el-tag>
                    <el-tag v-if=" scope.row.maintenanceGrade===3" type="danger">三级</el-tag>
                </template>
            </el-table-column>

            <el-table-column
                    sortable
                    prop="maintenanceExpense"
                    label="保养费用"
            width="100">
                <template slot-scope="scope">
                    {{ scope.row.maintenanceExpense }}元
                </template>
            </el-table-column>

            <el-table-column
                    prop="maintenancePeriodDate"
                    label="保养周期（时间）"
            width="100">
            </el-table-column>

            <el-table-column
                    prop="maintenancePeriodKm"
                    label="保养周期（公里数）"
            width="105">
            </el-table-column>

            <el-table-column
                    prop="maintenanceState"
                    label="状态"
                    width="80">
                <template slot-scope="scope">
                    <el-tag v-if=" scope.row.maintenanceState===0" type="danger">未保养</el-tag>
                    <el-tag v-if=" scope.row.maintenanceState===1" type="success">已保养</el-tag>
                    <el-tag v-if=" scope.row.maintenanceState===2" type="warning">保养中</el-tag>
                </template>
            </el-table-column>

            <el-table-column label="操作" width="240">
                <template slot-scope="scope">
                    <el-button-group>
                        <el-button
                                size="small" icon="el-icon-view"
                                type="success"
                                @click="viewForm(scope.row)">查看
                        </el-button>
                        <el-button
                                size="small" icon="el-icon-edit"
                                type="primary"
                                @click="handleEdit(scope.$index, scope.row)">编辑
                        </el-button>
                        <el-button
                                size="small"
                                type="danger" icon="el-icon-delete"
                                @click="handleDelete(scope.$index, scope.row)">删除
                        </el-button>
                    </el-button-group>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination style="margin-top: 10px"
                       background
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page="param.pageNum"
                       :page-sizes="[5, 10, 15]"
                       :page-size="param.pageSize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="pageBean.total">
        </el-pagination>
    </el-card>

    <!-- 添加对话框 -->
    <el-dialog
            title="车辆保养管理"
            :visible.sync="dialogVisible"
            width="550px"
            top center
            :before-close="resetForm">

        <!-- 表单 -->
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm" :disabled="disabled">
            <el-form-item label="车牌号" prop="carId" label-width="150px">
                <el-select
                        v-model="ruleForm.carId" style="width:250px"
                        filterable
                        clearable
                        remote
                        reserve-keyword
                        placeholder="请输入车牌号"
                        :remote-method="remoteMethodCarNumber"
                        :loading="loading">
                    <el-option
                            v-for="item in car"
                            :key="item.id"
                            :label="item.carNumber"
                            :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="车架号" prop="carId" label-width="150px">
                <el-select
                        v-model="ruleForm.carId" style="width:250px"
                        filterable
                        clearable
                        remote
                        reserve-keyword
                        placeholder="请输入车架号"
                        :remote-method="remoteMethod"
                        :loading="loading">
                    <el-option
                            v-for="item in car"
                            :key="item.id"
                            :label="item.frameNumber"
                            :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="保养级别" prop="maintenanceGrade" label-width="150px">
                <el-select v-model="ruleForm.maintenanceGrade" placeholder="请选择保养级别" @change="changeGrade()" style="width:250px">
                    <el-option
                            v-for="item in grade"
                            :key="item.id"
                            :label="item.label"
                            :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="保养周期（公里数）" prop="maintenancePeriodKm" label-width="150px">
                <el-input v-model="ruleForm.maintenancePeriodKm" placeholder="请填写公里数" style="width:250px"></el-input>
            </el-form-item>

            <el-form-item label="保养周期（时间）" prop="maintenancePeriodDate" label-width="150px">
                <el-input v-model="ruleForm.maintenancePeriodDate" placeholder="请填写时间" style="width:250px"></el-input>
            </el-form-item>

            <el-form-item label="保养费用" prop="maintenanceExpense" label-width="150px">
                <el-input v-model="ruleForm.maintenanceExpense" placeholder="请输入保养费用" style="width:250px"></el-input>
            </el-form-item>
            <!-- 这里要设置value-format格式，不然提交到服务器无法转成JSON -->
            <el-form-item label="保养日期" prop="maintenanceDate" label-width="150px">
                <el-date-picker style="width: 250px;"
                                v-model="ruleForm.maintenanceDate"
                                value-format="yyyy-MM-dd"
                                type="date"
                                placeholder="年-月-日">
                </el-date-picker>
            </el-form-item>

            <el-form-item label="当前保养状态" prop="maintenanceState" label-width="150px">
                <el-radio-group v-model="ruleForm.maintenanceState">
                    <el-radio :label="0">未保养</el-radio>
                    <el-radio :label="1">已保养</el-radio>
                    <el-radio :label="2">保养中</el-radio>
                </el-radio-group>
            </el-form-item>

        </el-form>

        <span slot="footer" class="dialog-footer">
                <el-button type="primary" v-if="showButton" @click="submitForm('ruleForm')">确定</el-button>
                <el-button @click="resetForm('ruleForm')">取消</el-button>
        </span>

    </el-dialog>

</div>
<script type="text/javascript">
    new Vue({
        el: "#app",
        data() {
            return {
                //一页数据对象
                pageBean: {},
                //提交参数对象
                param: {
                    maintenanceDate: null,
                    maintenanceState: null,
                    pageNum: 1,
                    pageSize: 5
                },
                //添加模式
                addModel: true,
                multipleSelection: [],
                dialogVisible: false,
                //查看按钮显示
                disabled:false,
                //确定按钮显示
                showButton:true,
                ruleForm: {},  //表单数据
                loading: false,  //是否远程加载
                options: [],  //车架号下拉选项列表
                car:[],
                carNumberOptions: [],  //车牌号下拉选项列表
                types: [
                    {
                        maintenanceState: 0,
                        name: '未保养'
                    }, {
                        maintenanceState: 1,
                        name: '已保养'
                    },{
                        maintenanceState: 2,
                        name: '保养中'
                    }
                ],
                grade:[
                    {
                        id: 1,
                        label: '一级'
                    }, {
                        id: 2,
                        label: '二级'
                    },{
                        id: 3,
                        label: '三级'
                    }
                ],
                rules: {
                    carNumber: [
                        {required: true, message: '车牌号不能为空', trigger: 'change'},
                        // {validator: validateNumberExists, trigger: 'blur'},
                    ],
                    frameNumber: [
                        {required: true, message: '请选择车架号', trigger: 'change'}
                    ],
                    maintenanceGrade: [
                        {required: true, message: '请选择保养等级', trigger: 'change'}
                    ],
                    maintenancePeriodDate: [
                        {required: true, message: '请选择保养周期（时间）', trigger: 'change'}
                    ],
                    maintenancePeriodKm: [
                        {required: true, message: '保养周期（公里）不能为空', trigger: 'blur'}
                    ],
                    maintenanceExpense: [
                        {required: true, message: '保养费用不能为空', trigger: 'blur'}
                    ],
                    maintenanceDate: [
                        {required: true, message: '保养日期不能为空', trigger: 'change'}
                    ],
                    maintenanceState: [
                        {required: true, message: '状态不能为空', trigger: 'change'}
                    ]
                }  //验证规则
            }
        },
        methods: {
            //查看
            viewForm(row){
                this.disabled=true;
                this.showButton=false;
                //清空表单写入不了问题
                this.dialogVisible = true;
                //复制数据
                let data = Object.assign({}, row);
                //将数据赋值给ruleForm
                this.ruleForm = data;
            },
            //费用绑定
            changeGrade(){
                this.ruleForm.maintenanceGrade === 1 ? this.ruleForm.maintenanceExpense = 20000 : this.ruleForm.maintenanceGrade === 2 ? this.ruleForm.maintenanceExpense = 40000 : this.ruleForm.maintenanceExpense = 60000;
            },
            //重置按钮搜索
            resetCondition(){
                this.param = {
                    maintenanceDate: null,
                    maintenanceState: null,
                    pageNum: 1,
                    pageSize: 5
                };
                this.findByPage();
            },
            //导出Exel
            exportExcel() {
                location.href = "/carHealth/export";
            },
            //上传成功
            handleSuccess(resp) {
                this.$message.success(resp);
                //重新加载数据
                this.findByPage();
            },
            //显示对话框
            showDialog() {
                //清空表单写入不了问题
                this.dialogVisible = true;
                this.showButton = true;
                //dom创建完成才能执行
                this.$nextTick(() => {
                    //清空表单和验证规则
                    this.$refs.ruleForm.clearValidate();
                    this.$refs.ruleForm.resetFields();
                    this.ruleForm = {};
                });
                //添加模式
                this.addModel = true;
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            //编辑按钮
            handleEdit(index, row) {
                //编辑模式
                this.addModel = false;
                this.disabled = false;
                this.showButton=true;
                //复制数据
                let data = Object.assign({}, row);
                //将数据赋值给ruleForm
                this.ruleForm = data;
                //打开对话框
                this.dialogVisible = true;
                //dom创建完成才能执行
                this.$nextTick(() => {
                    //清空验证规则
                    this.$refs.ruleForm.clearValidate();
                });
            },
            //删除
            handleDelete(index, row) {
                this.$confirm(`此操作将永久删除车辆保养记录：${row.carNumber}, 是否继续?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //调用服务器端来删除
                    axios.get(`/carHealth/deleteById?id=${row.id}`).then(resp => {
                        let result = resp.data;
                        if (result.code) {
                            this.$message.success(result.message);
                        } else {
                            this.$message.error("删除车辆保养记录失败");
                        }
                        //重新加载
                        this.findByPage();
                    });
                }).catch(() => {
                    //什么也不写
                });
            },
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.param.pageSize = val;
                this.findByPage();
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.param.pageNum = val;
                this.findByPage();
            },
            //查询按钮
            onSubmit() {
                this.findByPage();
            },
            //分页查询
            findByPage() {
                axios.post("/carHealth/findPage", this.param).then(resp => {
                    //resp.data得到Result对象，再获取其中data属性
                    this.pageBean = resp.data.data;
                });
            },
            //添加
            add() {
                axios.post("/carHealth/save", this.ruleForm).then(resp => {
                    let result = resp.data;
                    if (result.code) {
                        this.$message.success(result.message);
                    }
                }).catch(err => {
                    this.$message.error("添加车辆保养记录失败，错误信息是：" + err.message);
                }).finally(() => {
                    this.ruleForm = {};
                    //清除验证错误信息
                    this.$refs.ruleForm.clearValidate();
                    this.dialogVisible = false;
                    //查询记录
                    this.findByPage();
                });
            },
            //修改
            update() {
                axios.post("/carHealth/update", this.ruleForm).then(resp => {
                    let result = resp.data;
                    if (result.code) {
                        this.$message.success(result.message);
                    }
                }).catch(err => {
                    this.$message.error("修改车辆保养记录失败，错误信息是：" + err.message);
                }).finally(() => {
                    this.ruleForm = {};
                    //清除验证错误信息
                    this.$refs.ruleForm.clearValidate();
                    this.dialogVisible = false;
                    //查询车位
                    this.findByPage();
                });
            },
            //批量删除
            deleteBatch() {
                //判断是否选中
                if (this.multipleSelection.length == 0) {
                    this.$message.warning("请先选中要删除的数据");
                    return;
                }
                //删除前确认
                this.$confirm(`此操作将永久删除${this.multipleSelection.length}条保养记录,是否继续?`, '提示',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                    //1.把对象数组转成id的数组 (row表示数组中每个元素)
                    let ids = this.multipleSelection.map(row => row.id);
                    console.log(ids);
                    //2.发送删除操作给服务器端
                    axios.post("/carHealth/deleteBatch", ids).then(resp => {
                        //获取删除的行数
                        let num = resp.data.data;
                        this.$message.success(`成功删除${num}条车辆保养记录`);
                        //重新加载表格数据
                        this.findByPage();
                    });
                }).catch(() => {
                    //不做什么
                });
            },
            //确定按钮
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        if (this.addModel) {
                            //添加方法
                            this.add();
                        } else {
                            this.update();
                        }
                    } else {
                        return false;
                    }
                });
            },
            resetForm(formName) {
                // this.$refs[formName].resetFields();
                this.$refs.ruleForm.resetFields();
                this.ruleForm = {};
                this.dialogVisible = false;
                this.disabled = false;//开启可编辑
            },
            //远程加载的方法, query输入的字符串 (车架名字)
            remoteMethod(query) {
                if (query !== '') {
                    //开始远程加载 (有个可以转动的图标)
                    this.loading = true;
                    //后台通过车架号模糊查询
                    axios.get(`/car/findByFrameNumber?frameNumber=${query}`).then(resp => {
                        this.loading = false;  //不转了
                        this.options = resp.data.data;
                    });
                } else {
                    this.options = [];
                }
            },
            //车牌号远程查找
            remoteMethodCarNumber(query) {
                if (query !== '') {
                    //开始远程加载 (有个可以转动的图标)
                    this.loading = true;
                    //后台通过车牌号模糊查询
                    axios.get(`/car/findByCarNumber?carNumber=${query}`).then(resp => {
                        this.loading = false;  //不转了
                        this.carNumberOptions = resp.data.data;
                    });
                } else {
                    this.carNumberOptions = [];
                }
            },
            //绑定car同一个id
            findCarList() {
                axios.get("/car/findCarList").then(resp => {
                    this.car = resp.data.data;
                })
            },
        },
        created() {
            this.findByPage();
            this.findCarList();
        }
    });
</script>
</body>
</html>